package com.ourteam.system.api;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.frame.web.ApplicationModel;
import com.ourteam.frame.web.MenuItem;
import com.ourteam.system.domain.ApplicationDomain;
import com.ourteam.system.service.ISystemApplicationService;
import com.ourteam.system.service.SystemApplicationServiceFactory;

public class SystemAccountMenuNodeBuilder extends AbstractTreeNodeBuilder<ApplicationDomain, MenuItem> {

	private final static ISystemApplicationService applicationService = SystemApplicationServiceFactory
			.getSystemApplicationService();

	@Override
	public MenuItem[] getTreeNodeObjects(ApplicationDomain parentObject) throws Exception {

		Subject subject = SecurityUtils.getSubject();

		ApplicationModel appModel = (ApplicationModel) subject.getPrincipal();

		return appModel.getMenuItems();

		// List<AppDomain> appDomains = appModel.getAppDomains();
		//
		// for (int i = 0; i < appDomains.size(); i++) {
		// if (appDomains.get(i).getId() == parentObject.getId()) {
		// return appDomains.get(i).getMenuItems();
		// }
		// }

		// return new MenuItem[0];
	}

	@Override
	public Object getNodeId(MenuItem childObject) {
		return childObject.getMenuId();
	}

	public boolean isLeaf(MenuItem childObject) throws Exception {

		return childObject.hasSubItems() == false;
	}

	@Override
	public String getNodeDefineId(MenuItem childObject) throws Exception {
		return "menuItem";
	}

	@Override
	public ApplicationDomain converToParentObject(Object parent) throws Exception {
		return applicationService.getApplicationDomainById(Long.parseLong(parent.toString()));
	}

	@Override
	public int getChildCount(MenuItem childObject) throws Exception {
		return ArrayUtils.isNotEmpty(childObject.getSubItems()) ? childObject.getSubItems().length : 0;
	}

}
